import React, { Component } from 'react';
// 搜索头部
import SearchBar from '../../components/SearchBar'
// antdui组件
import { Flex, Toast } from 'antd-mobile'
// 获取当前城市
import { getCurrentCity } from '../../utils/city'
import styles from './index.module.scss'
// 筛选组件
import Filter from '../../components/Filter';
// 导入房屋列表每一项
import HouseItem from '../../components/HouseItem'
// 导入贴顶组件
import Affix from '../../components/Affix'
// 长列表渲染组件
import {
    AutoSizer,
    InfiniteLoader,
    List,
    WindowScroller,
} from "react-virtualized";

class index extends Component {
    constructor() {
        super()
        this.state = {
            cityName: "深圳",
            count: 0,
            houseList: null
        }
    }
    // 定义一个实例属性filters,这个属性用于获取房源列表的参数
    filters = {}
    // dom刚渲染时的生命周期钩子
    async componentDidMount() {
        const { label, value } = await getCurrentCity()
        this.setState({
            cityName: label
        })
        this.value = value
        // 获取第一页的数据
        this.getHouseListData()
    }
    // 发送请求获取房源列表数据
    conditionChange = (data) => {
        console.log(data, "data")
        // 处理area和subway
        this.filters.area = null
        this.filters.subway = null
        if (data.area.length > 2) {
            this.filters[data.area[0]] = data.area[2] == "null" ? data.area[1] : data.area[2]
        }
        // 出租方式
        if (data.mode.length > 0) {
            this.filters.rentType = data.mode[0]
        } else {
            this.filters.rentType = null
        }
        // 租金
        if (data.price.length > 0) {
            this.filters.price = data.price[0]
        } else {
            this.filters.price = null
        }
        // 更多
        if (data.more.length > 0) {
            this.filters.more = data.more.join(",")
        } else {
            this.filters.more = null
        }
        console.log(this.filters, "this.filters")
        // 根据获取的条件,查询房源列表数据
        this.getHouseListData()
    }
    // 获取房源列表信息
    getHouseListData = async () => {
        Toast.loading("数据加载中", 0)
        const res = await this.axios.get("/houses", {
            params: {
                cityId: this.value,
                ...this.filters,
                start: 1,
                end: 20
            }
        })
        if (res.data.body.count > 0) {
            Toast.info(`共查询到 ${res.data.body.count}  套房源`, 1.5);
            this.setState({
                count: res.data.body.count,
                houseList: res.data.body.list
            })
        }
        console.log(res, "==========")
        Toast.hide();
    }
    // 无限加载器 加载更多的行
    // 当必须加载更多行时要调用的回调,一旦数据加载完成,应解决返回的Promise.将用于确定何时使用新加载的数据刷新列表,响应单个滚动事件,可以多次调用此回调
    loadMoreRows = ({ startIndex, stopIndex }) => {
        return new Promise(async (resolve, reject) => {
            console.log("promise 数据加载中")
            Toast.loading("数据加载中", 0);
            const res = await this.axios.get("/houses", {
                params: {
                    cityId: this.value,
                    ...this.filters,
                    start: startIndex,
                    end: stopIndex
                }
            })
            Toast.hide()
            if (res.data.body.count) {
                this.setState({
                    count: res.data.body.count,
                    houseList: [...this.state.houseList, ...res.data.body.list]
                }, () => {
                    resolve()
                })
            }
        })
    }
    // 判断数据是否加载完毕
    // 要用取反将其转化为布尔值类型
    isRowLoaded = ({ index }) => {
        return !!this.state.houseList[index]
    }
    // 渲染行
    rowRenderer = ({
        index, // Index of row
        isScrolling, // The List is currently being scrolled
        isVisible, // This row is visible within the List (eg it is not an overscanned row)
        key, // Unique key within array of rendered rows
        parent, // Reference to the parent List (instance)
        style, // Style object to be applied to row (to position it);
        // This must be passed through to the rendered row element.
    }) => {
        const data = this.state.houseList[index]
        if (!data) {
            return (
                <div key={key} style={style}>
                    <div className={styles.loading}>loading</div>
                </div>
            )
        } else {
            return (
                <div key={key} style={style}>
                    <HouseItem {...data} />
                </div>
            );
        }
    }
    render() {
        const { count } = this.state
        return (
            <div className={styles.root}>
                <Flex className={styles.listHeader}>
                    <i className="iconfont icon-back" onClick={() => { this.props.history.goBack() }}></i>
                    <SearchBar className={styles.mySearchBar} cityName={this.state.cityName} />
                </Flex>
                {/* 筛选组件 */}
                <Affix>
                    <Filter onConditionChange={this.conditionChange} />
                </Affix>
                {/* 房源列表 */}
                <div className={styles.houseList}>
                    <WindowScroller>
                        {({ height, isScrolling, scrollTop }) => (
                            <AutoSizer>
                                {({ width }) => (
                                    <InfiniteLoader
                                        isRowLoaded={this.isRowLoaded}
                                        loadMoreRows={this.loadMoreRows}
                                        rowCount={count}
                                        minimumBatchSize={20}
                                    >
                                        {({ onRowsRendered, registerChild }) => (
                                            <List
                                                height={height}
                                                onRowsRendered={onRowsRendered}
                                                autoHeight
                                                rowCount={count}
                                                isScrolling={isScrolling}
                                                scrollTop={scrollTop}
                                                rowHeight={120}
                                                rowRenderer={this.rowRenderer}
                                                width={width}
                                            />
                                        )}
                                    </InfiniteLoader>
                                )}
                            </AutoSizer>
                        )}
                    </WindowScroller>,
                </div>
            </div>
        );
    }
}

export default index;